package org.example.node;

import java.util.HashSet;
import java.util.Set;

/**
 * @author liyishan
 * @date 2024/2/19 09:34
 * @apiNote
 */

public class Test00141HasCycle {
    public static boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<>();
        while(head != null){
            if(!seen.add(head)){
                return true;
            }
            head = head.next;
        }
        return false;
    }

    public static boolean hasCycle1(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != fast){
            if(fast == null || fast.next == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

    public boolean hasCycle2(ListNode head) {
        ListNode A=head;//快指针
        ListNode B=head;//慢指针
        while(A!=null&&A.next!=null) {
            A=A.next.next;//快指针一次走两步
            B=B.next;//慢指针一次走一步
            //当两个结点相同时，意思就是相遇了
            if(A==B) {
                return true;//返回正确
            }
        }
        return false;//当出了循环说明这个链表没有环，返回错误
    }
}
